﻿using AutoMapper;
using MediatR;
using MyMES.Domain.yjb;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Read.API.Application.Commends.settingCommand;
using MyMES.Read.API.FileNlog;

namespace MyMES.Read.API.Application.CommendHandlers.settingCommand
{
    public class ShoeTBCommandHandlers : IRequestHandler<ShoeTBCommand, APIPaging<List<TransferOrder>>>
    {
        private readonly IBaseRepository<TransferOrder> accreop;
        private readonly Nolgs nlogselvse;
        private readonly IMapper mapper;

        public ShoeTBCommandHandlers(IBaseRepository<TransferOrder> accreop, Nolgs nlogselvse)
        {
            this.accreop = accreop;
            this.nlogselvse = nlogselvse;
            this.mapper = mapper;
        }
        /// <summary>
        /// 调拨显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIPaging<List<TransferOrder>>> Handle(ShoeTBCommand request, CancellationToken cancellationToken)
        {
            var startTime = System.DateTime.Now;
            try
            {
                APIPaging<List<TransferOrder>> result = new APIPaging<List<TransferOrder>>();
                result.Code = APIEnum.查询失败;
                result.Msg = "查询成功";
                string sql = "select * from TransferOrder where IsDelete=true ORDER BY TransferOrderId DESC";

                var list = await accreop.SelectAsync(sql);

                if (!string.IsNullOrEmpty(request.TransferOrderNumber))
                {
                    list = list.Where(x => x.TransferOrderNumber.Contains(request.TransferOrderNumber)).ToList();
                }
                if (!string.IsNullOrEmpty(request.TransferOrderName))
                {
                    list = list.Where(x => x.TransferOrderName.Contains(request.TransferOrderName)).ToList();
                }
                if (!string.IsNullOrEmpty(request.TransferOrderType))
                {
                    list = list.Where(x => x.TransferOrderType.Contains(request.TransferOrderType)).ToList();
                }

                result.TotalCount = list.Count;
                result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.Size);
                list = list.Skip((request.Index - 1) * request.Size).Take(request.Size).ToList();

                result.data = list;
                return result;
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                var endTime = System.DateTime.Now;

                var durationInDays = (endTime - startTime).Days;
                nlogselvse.GetNlogs(
                    request.TransferOrderName ?? "Unknow", "仓库显示列表", "False", durationInDays, "异常信息"
                    );
            }
        }
    }
}
